import axios                  from "axios";
import {close, fail, loading} from '../until/helper'
import qs                     from 'qs'

const HttpRequest = {
    getRequest({url, data = {}, method = "GET"}) {
        loading();
        return new Promise((resolve, reject) => {
            this._getRequest(url, resolve, reject, data, method);
        });
    },
    _getRequest: function (url, resolve, reject, data = {}, method = "GET") {
        let format = method.toLocaleLowerCase() === 'get' ? 'params' : 'data';
        axios({
            url: url,
            method: method,
            [format]: qs.stringify(data),
            header: {
                'content-type': 'application/json',
            }
        }).then(res => {
            close();
            if (res.status === 200) {
                return resolve(res.data);
            } else {
                fail();
            }
        }).catch(() => {
            close();
            reject();
            fail();
        })
    }
};

export {HttpRequest};